package com.caifu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.caifu.bean.Result;
import com.caifu.bean.ResultUtil;
import com.caifu.mapper.DeviceUserMapper;
import com.caifu.mapper.UserCDUserMapper;
import com.caifu.mapper.UserCdRecordMapper;
import com.caifu.mapper.UserMapper;
import com.caifu.pojo.CDRecord;
import com.caifu.pojo.CDUser;
import com.caifu.pojo.CUser;
import com.caifu.pojo.SysUser;
import com.caifu.service.UserService;
import com.caifu.util.SendingSms;
import com.caifu.util.Utils;
import com.caifu.vo.Devo;
import com.caifu.vo.UserVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional(rollbackFor = RuntimeException.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, CUser> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private DeviceUserMapper deviceUserMapper;

    @Resource
    private UserCDUserMapper userCDUserMapper;

    @Resource
    private UserCdRecordMapper userCdRecordMapper;

    @Override
    public List<Map<String, Object>> listUserInfo(Integer orgId, Integer deptId) throws Exception {
        try {
            return userMapper.listUserInfo(orgId, deptId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception();
        }
    }


    @Override
    public CUser getUserInfo(String userNo) throws Exception {
        try {
            return userMapper.selectById(userNo);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception();
        }
    }


    @Override
    public PageInfo<UserVo> getUserList(SysUser user, UserVo vo) {
        Map<String, Object> params = new HashMap<>();
        List<UserVo> userList = new ArrayList<>();
        params.put("userName", vo.getUserName());
        params.put("deptId", vo.getDeptName());
        params.put("userType", vo.getType());
        //判断用户类型
        PageHelper.startPage(vo.getCurrentPage(), vo.getPageSize());
        if ("1".equals(user.getUserType())) {
            params.put("orgId", user.getRelativeId());
            userList = userMapper.getUserList(params);
        } else if ("2".equals(user.getUserType())) {
            params.put("dept", user.getRelativeId());
            userList = userMapper.getUserList(params);
        }
        for (UserVo userVo : userList) {
            if ("1".equals(userVo.getType())) {
                userVo.setType("员工");
            } else {
                userVo.setType("访客");
            }

            if ("1".equals(userVo.getUserSex())) {
                userVo.setUserSex("男");
            } else {
                userVo.setUserSex("女");
            }
        }


        return new PageInfo<UserVo>(userList);
    }

    @Override
    public Result addOrUpdate(CUser cUser, SysUser user) throws Exception {
        //id为空添加user
        if (Utils.isNull(cUser.getUserNo())) {
            //卡号不为空校验卡号是否存在
            if (Utils.isNotNull(cUser.getCardNo()) && countCard(cUser.getCardNo())) {
                return ResultUtil.error(997, "卡号已存在");
            }
            cUser.setCreateTime(new Date());
            cUser.setStatus("1");
            if ("../static/img/moren.png".equals(cUser.getUserPhoto()) || "/AccessManage/img/moren.png".equals(cUser.getUserPhoto())) {
                cUser.setUserPhoto("");
            }
            userMapper.insert(cUser);
            //关联设备
            if (cUser.getDevos().size() > 0) {
                List<Devo> devos = cUser.getDevos();
                for (Devo devo : devos) {
                    CDUser cdUser = new CDUser();
                    cdUser.setUserNo(cUser.getUserNo());
                    cdUser.setDeviceId(devo.getDevId());
                    cdUser.setCreateTime(new Date());
                    cdUser.setStatus("1");
                    //判断用户类型
                    if ("1".equals(cUser.getUserType())) {
                        //判断是否勾选全天
                        if (Utils.isNull(devo.getStartTime()) && Utils.isNull(devo.getEndTime())) {
                            cdUser.setType("2");
                            cdUser.setStartTime(geshiDate("00:00:00"));
                            cdUser.setEndTime(geshiDate("23:59:59"));
                        } else {
                            cdUser.setStartTime(devo.getStartTime());
                            cdUser.setEndTime(devo.getEndTime());
                            cdUser.setType("1");
                        }
                        cdUser.setIsIssued("0");
                    } else {
                        cdUser.setStartTime(devo.getStartTime());
                        cdUser.setEndTime(devo.getEndTime());
                        cdUser.setVisitDate(devo.getVisitDate());
                        String code = Utils.getRandom(4);
                        //校验code是否存在并且首位不为0
                        boolean flag = checkCode(code, devo.getVisitDate(), devo.getDevId());
                        while (flag) {
                            code = Utils.getRandom(4);
                            flag = checkCode(code, devo.getVisitDate(), devo.getDevId());
                        }
                        cdUser.setPassword(code);
                        cdUser.setType("1");
                        //发送访客码
                        SendingSms.sendingSMS(cUser.getMobile(), code);
                    }
                    userCDUserMapper.insert(cdUser);
                }
            }
        } else {
            //卡号不为空校验卡号是否存在
            if (Utils.isNotNull(cUser.getCardNo()) && countCard(cUser.getCardNo())) {
                return ResultUtil.error(997, "卡号已存在");
            }

            //查询user
            CUser eUser = userMapper.selectById(cUser.getUserNo());
            eUser.setUserName(cUser.getUserName());
            eUser.setUserSex(cUser.getUserSex());
            eUser.setMobile(cUser.getMobile());
            eUser.setDeptId(cUser.getDeptId());
            eUser.setUserType(cUser.getUserType());
            //判断用户类型
            if ("1".equals(cUser.getUserType())) {
                eUser.setCardNo(cUser.getCardNo());
                eUser.setUserPhoto(cUser.getUserPhoto());
            }
            userMapper.updateById(eUser);
            //将之前关联的设备删除
            List<CDUser> cdUsers = userCDUserMapper.selectList(new QueryWrapper<CDUser>()
                    .eq("user_no", cUser.getUserNo())
                    .eq("status", 1));
            if (cdUsers.size() > 0) {
                for (CDUser cdUser : cdUsers) {
                    cdUser.setStatus("9");
                    userCDUserMapper.updateById(cdUser);
                }
            }

            //关联设备
            if (cUser.getDevos().size() > 0) {
                List<Devo> devos = cUser.getDevos();
                for (Devo devo : devos) {
                    CDUser cdUser = new CDUser();
                    cdUser.setUserNo(cUser.getUserNo());
                    cdUser.setDeviceId(devo.getDevId());
                    cdUser.setCreateTime(new Date());
                    cdUser.setStatus("1");
                    cdUser.setIsIssued("0");
                    //判断用户类型
                    if ("1".equals(cUser.getUserType())) {
                        //判断是否勾选全天
                        if (Utils.isNull(devo.getStartTime()) && Utils.isNull(devo.getEndTime())) {
                            cdUser.setType("2");
                            cdUser.setStartTime(geshiDate("00:00:00"));
                            cdUser.setEndTime(geshiDate("23:59:59"));
                        } else {
                            cdUser.setStartTime(devo.getStartTime());
                            cdUser.setEndTime(devo.getEndTime());
                            cdUser.setType("1");
                        }
                        //校验当前id是否存在
                        if (cdUsers.size() > 0) {
                            for (CDUser cdUser3 : cdUsers) {
                                if (cdUser3.getDeviceId().equals(devo.getDevId())) {
                                    cdUser.setIsIssued("1");
                                }
                            }
                        }
                    } else {
                        cdUser.setStartTime(devo.getStartTime());
                        cdUser.setEndTime(devo.getEndTime());
                        cdUser.setVisitDate(devo.getVisitDate());
                        //校验code是否存在
                        String code = Utils.getRandom(4);
                        boolean flag = checkCode(code, devo.getVisitDate(), devo.getDevId());
                        while (flag) {
                            code = Utils.getRandom(4);
                            flag = checkCode(code, devo.getVisitDate(), devo.getDevId());
                        }
                        cdUser.setPassword(code);
                        cdUser.setType("1");
                    }
                    userCDUserMapper.insert(cdUser);
                    if (cdUsers.size() > 0) {
                        for (CDUser cdUser2 : cdUsers) {
                            //如果用户类型为用户
                            if ("1".equals(cUser.getUserType()) && cdUser2.getDeviceId().equals(devo.getDevId()) && "1".equals(cdUser2.getIsIssued())) {
                                //添加记录
                                CDRecord cdRecord = new CDRecord();
                                cdRecord.setUserNo(cUser.getUserNo());
                                cdRecord.setDeviceId(devo.getDevId());
                                cdRecord.setCreateTime(new Date());
                                cdRecord.setStatus("0");
                                cdRecord.setIssuedState("0");
                                userCdRecordMapper.insert(cdRecord);
                            }
                        }
                    }
                }

            }
        }
        return ResultUtil.success(200, "保存成功");
    }

    /**
     * 校验code是否存在
     *
     * @param code
     * @param visitDate
     * @param devId
     * @return
     */
    private boolean checkCode(String code, Date visitDate, Integer devId) {
        if ("0".equals(code.charAt(0))) {
            return true;
        }
        Integer count = userCDUserMapper.selectCount(new QueryWrapper<CDUser>()
                .eq("device_id", devId)
                .eq("visit_date", visitDate)
                .eq("password", code)
                .eq("status", 1));
        if (count > 0) {
            return true;
        }
        return false;
    }

    /**
     * 判断卡号是否存在
     *
     * @param cardNo
     * @return
     */
    private boolean countCard(String cardNo) {
        Integer count = userMapper.selectCount(new QueryWrapper<CUser>().eq("card_no", cardNo));
        if (count > 0) {
            return true;
        }
        return false;
    }

    @Override
    public CUser getUserById(SysUser user, String userNo) {
        return userMapper.selectUserInfo(userNo);
    }

    @Override
    public Result deleteById(String userNo) {
        CUser cUser = userMapper.selectById(userNo);
        cUser.setStatus("9");
        userMapper.updateById(cUser);

        //将之前关联的设备删除
        List<CDUser> cdUsers = userCDUserMapper.selectList(new QueryWrapper<CDUser>()
                .eq("user_no", userNo)
                .eq("status", 1));
        for (CDUser cdUser : cdUsers) {
            cdUser.setStatus("9");
            userCDUserMapper.updateById(cdUser);
        }

        return ResultUtil.success(200, "删除成功");
    }

    /**
     * 返回date
     */
    private Date geshiDate(String date) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
        return format.parse(date);
    }
}
